const dayjs = require('dayjs');
/**
 * 研发项目数据迁移脚本
 */

const cloud = wx.cloud;
const db = cloud.database();
const BATCH_SIZE = 100; // 每批处理的数据量

// 项目名称映射对照表
// 方便查看旧字段和新字段的对应关系
const FIELD_MAPPING = {
  // 基础标识信息
  '_id': 'id',
  'PROJECT_CODE': 'projectCode',
  'PROJECT_NAME': 'name',
  'code': 'code',
  
  // 分类与描述信息
  'PROJECT_TYPE': 'projectType',
  'PROJECT_TYPE_NAME': 'projectTypeName',
  'RA_CATEGORY': 'category',
  'applicationType': 'applicationType',
  'PROJECT_DESC': 'description',
  'projectDesc': 'projectDesc',
  
  // 人员信息
  'PROJECT_CUSTOMER_NAME': 'customerName',
  'PROJECT_CUSTOMER_ID': 'customerId',
  'APPLICANT_ID': 'applicantId',
  'APPLICANT_NAME': 'applicantName',
  'PROJECT_MANAGER_ID': 'projectLeadId',
  'PROJECT_MANAGER_NAME': 'projectLead',
  'PROJECT_TEAM_MEMBER_IDS': 'teamMembers',
  
  // 项目管理和状态信息
  'PROJECT_STATUS': 'level1',
  'PROJECT_SUB_STATUS': 'level2',
  'PROJECT_ACTIVE_STATUS': 'level3',
  'PROJECT_SUB_ACTIVE_STATUS': 'level4', 
  'PROJECT_STATUS_DESC': 'statusDesc',
  'PROJECT_PRIORITY': 'priority',
  
  // 时间信息
  'ADD_TIME': 'createTime',
  'CREATE_TIME': 'createTime',
  'EDIT_TIME': 'updateTime',
  'UPDATE_TIME': 'updateTime',
  'PROJECT_START_DATE': 'startDate',
  'startDate': 'startDate',
  'PROJECT_END_DATE': 'endDate',
  'PROJECT_DEADLINE': 'deadline',
  'PROJECT_PLAN_START_DATE': 'planStartDate',
  'PROJECT_PLAN_END_DATE': 'planEndDate',
  'PROJECT_STATUS_UPDATE_TIME': 'stateTime',
  'PROJECT_STATUS_EXPIRE_TIME': 'stateExpireTime',
  'branchId': 'branchId',
  'branchName': 'branchName',
  'PROJECT_TITLE': 'PROJECT_TITLE'
};

// 状态映射 - 将旧状态转换为level状态
const STATUS_MAPPING = {
  // 项目状态映射
  'PROJECT_STATUS': {
    1: 1, // 项目审核
    2: 2, // 休眠
    3: 3, // 活动
    4: 99 // 已完成
  },
  
  // 子状态映射
  'PROJECT_SUB_STATUS': {
    'director': 'director',
    'rd_manager': 'rd_manager',
    'assignment': 'assignment',
    'review': 'review',
    'archive': 'archive'
  },
  
  // 活动状态映射
  'PROJECT_ACTIVE_STATUS': {
    'hardware_confirm': 'hardware_confirm',
    'hardware': 'hardware',
    'debug': 'debug',
    'data_sync': 'data_sync',
    'testing': 'testing',
    'customer_confirm': 'customer_confirm',
    'order_preparation': 'order_preparation',
    'production': 'production',
    'product_feedback': 'product_feedback'
  }
};

/**
 * 迁移研发项目数据
 */
async function migrateProjects() {
  console.log('开始迁移研发项目数据...');
  
  // 查询总记录数
  const countResult = await db.collection('research_project').count();
  const total = countResult.total;
  console.log(`共发现${total}条记录需要迁移`);
  
  // 批量处理
  const batchCount = Math.ceil(total / BATCH_SIZE);
  
  for (let i = 0; i < batchCount; i++) {
    console.log(`处理第${i + 1}/${batchCount}批数据`);
    
    // 查询一批数据
    const records = await db.collection('research_project')
      .skip(i * BATCH_SIZE)
      .limit(BATCH_SIZE)
      .get();
    
    if (!records || !records.data || records.data.length === 0) {
      console.log('没有找到记录，跳过本批次');
      continue;
    }
    
    // 处理每条记录
    for (const oldRecord of records.data) {
      await migrateProjectRecord(oldRecord);
    }
    
    console.log(`已完成第${i + 1}批数据迁移`);
  }
  
  console.log('项目数据迁移完成');
}

/**
 * 迁移单条项目记录
 * @param {Object} oldRecord 旧记录
 */
async function migrateProjectRecord(oldRecord) {
  try {
    // 转换为新格式
    const newRecord = convertToNewFormat(oldRecord);
    
    // 更新数据库
    await db.collection('plm_research_project').add({
      data: newRecord
    });
    
    console.log(`成功迁移项目: ${oldRecord._id || oldRecord.PROJECT_CODE || '未知ID'}`);
    return true;
  } catch (error) {
    console.error('迁移记录失败:', error);
    console.error('失败的记录:', oldRecord._id || oldRecord.PROJECT_CODE || '未知ID');
    return false;
  }
}

/**
 * 将旧格式数据转换为新格式
 * @param {Object} oldRecord 旧格式记录
 * @returns {Object} 新格式记录
 */
function convertToNewFormat(oldRecord) {
  const now = Math.floor(dayjs().valueOf() / 1000);
  
  // 创建新记录基本结构
  const newRecord = {
    // 基础标识信息
    _id: oldRecord._id,
    projectCode: oldRecord.PROJECT_CODE || oldRecord.code || generateProjectCode(),
    model: oldRecord.PROJECT_NAME || oldRecord.name || oldRecord.PROJECT_TITLE || '未命名项目',
    
    // 分类与描述信息
    projectType: oldRecord.PROJECT_TYPE || 1,
    projectTypeName: oldRecord.PROJECT_TYPE_NAME || '电机控制',
    category: oldRecord.RA_CATEGORY || oldRecord.category || '研发',
    applicationType: oldRecord.applicationType || '',
    description: oldRecord.PROJECT_DESC || oldRecord.description || oldRecord.projectDesc || '',
    projectDesc: oldRecord.projectDesc || oldRecord.PROJECT_DESC || oldRecord.description || '',
    
    // 客户信息
    customerName: oldRecord.PROJECT_CUSTOMER_NAME || oldRecord.customerName || '',
    customerId: oldRecord.PROJECT_CUSTOMER_ID || oldRecord.customerId || '',
    
    // 申请人信息
    applicantId: oldRecord.APPLICANT_ID || oldRecord.applicantId || '',
    applicantName: oldRecord.APPLICANT_NAME || oldRecord.applicantName || '',
    
    // 项目人员信息
    projectLeadId: oldRecord.PROJECT_MANAGER_ID || oldRecord.projectLeadId || '',
    projectLead: oldRecord.PROJECT_MANAGER_NAME || oldRecord.projectLead || '',
    teamMembers: oldRecord.PROJECT_TEAM_MEMBER_IDS || oldRecord.teamMembers || [],
    
    // 项目管理和状态信息（转换为level体系）
    level1: mapStatus(oldRecord.PROJECT_STATUS, STATUS_MAPPING.PROJECT_STATUS, 1),
    level2: mapStatus(oldRecord.PROJECT_SUB_STATUS, STATUS_MAPPING.PROJECT_SUB_STATUS, ''),
    level3: mapStatus(oldRecord.PROJECT_ACTIVE_STATUS, STATUS_MAPPING.PROJECT_ACTIVE_STATUS, ''),
    level4: oldRecord.PROJECT_SUB_ACTIVE_STATUS || '',
    statusDesc: oldRecord.PROJECT_STATUS_DESC || '',
    priority: oldRecord.PROJECT_PRIORITY || oldRecord.priority || 'normal',
    
    // 分支相关信息
    branchId: oldRecord.branchId || '',
    branchName: oldRecord.branchName || '主分支',
    
    // 时间信息
    createTime: oldRecord.ADD_TIME || oldRecord.CREATE_TIME || oldRecord.createTime || now,
    updateTime: oldRecord.EDIT_TIME || oldRecord.UPDATE_TIME || oldRecord.updateTime || now,
    
    // 项目时间点
    startDate: oldRecord.PROJECT_START_DATE || oldRecord.startDate || 0,
    endDate: oldRecord.PROJECT_END_DATE || oldRecord.endDate || 0,
    deadline: oldRecord.PROJECT_DEADLINE || oldRecord.deadline || 0,
    
    // 计划时间点
    planStartDate: oldRecord.PROJECT_PLAN_START_DATE || oldRecord.planStartDate || 0,
    planEndDate: oldRecord.PROJECT_PLAN_END_DATE || oldRecord.planEndDate || 0,
    
    // 状态时间点
    stateTime: oldRecord.PROJECT_STATUS_UPDATE_TIME || oldRecord.stateTime || now,
    stateExpireTime: oldRecord.PROJECT_STATUS_EXPIRE_TIME || oldRecord.stateExpireTime || 0,
    
    // 样品信息
    hasSample: oldRecord.hasSample || '无',
    sampleCount: oldRecord.sampleCount || '',
    sampleImages: oldRecord.sampleImages || [],
    
    // 迁移标记
    _migrated: true,
    _migratedTime: now,
    _sourceId: oldRecord._id
  };
  
  // 复制电机控制参数（如果存在）
  const motorParams = [
    'workTemp', 'certification', 'lowPower', 'startupTime', 'conformalCoating',
    'ratedVoltage', 'maxPower', 'maxSpeed', 'polePairs', 'hasHall', 'hasFG', 'hasBrake',
    'controlMode', 'controlAlgorithm', 'rotation', 'controlInterface',
    'stallProtection', 'overvoltageProtection', 'undervoltageProtection', 
    'temperatureProtection', 'overcurrentProtection', 'currentLimitProtection',
    'blockageProtection', 'phaseProtection'
  ];
  
  motorParams.forEach(param => {
    if (oldRecord[param] !== undefined) {
      newRecord[param] = oldRecord[param];
    }
  });
  
  return newRecord;
}

/**
 * 映射状态值
 * @param {*} oldStatus 旧状态值
 * @param {Object} mapping 映射表
 * @param {*} defaultValue 默认值
 */
function mapStatus(oldStatus, mapping, defaultValue) {
  if (oldStatus === undefined || oldStatus === null) {
    return defaultValue;
  }
  
  return mapping[oldStatus] !== undefined ? mapping[oldStatus] : oldStatus;
}

/**
 * 生成项目编号
 * @returns {string} 项目编号
 */
function generateProjectCode() {
  const date = dayjs();
  const year = date.year();
  const month = (date.month() + 1).format("YYYY-MM-DD HH:mm:ss").padStart(2, '0');
  const random = Math.floor(Math.random() * 10000).format("YYYY-MM-DD HH:mm:ss").padStart(4, '0');
  
  return `RP${year}${month}${random}`;
}

/**
 * 执行迁移
 */
export async function runMigration() {
  try {
    console.log('开始数据迁移过程...');
    
    // 检查目标集合是否存在，不存在则创建
    try {
      await db.createCollection('plm_research_project');
      console.log('创建目标集合: plm_research_project');
    } catch (error) {
      console.log('目标集合已存在，跳过创建');
    }
    
    // 迁移项目数据
    await migrateProjects();
    
    console.log('数据迁移完成');
    return { success: true, message: '数据迁移成功' };
  } catch (error) {
    console.error('数据迁移失败:', error);
    return { success: false, message: '数据迁移失败: ' + error.message };
  }
}

// 导出迁移函数
module.exports = {
  runMigration
}; 